﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Channels;
using System.Runtime.Serialization.Formatters;
using System.Collections;
using System.Runtime.Remoting.Channels.Tcp;

namespace IM.gerenciadores
{
    class GerenciadorDeConexaoCliente
    {
        private static TcpChannel chan;
        public static TcpChannel Chan
        {
            get { return GerenciadorDeConexaoCliente.chan; }
            set { GerenciadorDeConexaoCliente.chan = value; }
        }

        public static InterfaceRemota.IServidor configuraServidor(
            String ip, String projeto)
        {
            return configuraServidor(ip, "9000", 8080, projeto);
        }

        public static InterfaceRemota.IServidor configuraServidor(
                String ip, String portaServidor, Int16 portaCliente, String projeto)
        {
            BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
            serverProvider.TypeFilterLevel = TypeFilterLevel.Full;

            IDictionary props = new Hashtable();
            props["port"] = portaCliente;
            string s = System.Guid.NewGuid().ToString();
            props["name"] = s;
            props["typeFilterLevel"] = TypeFilterLevel.Full;
            Chan = new TcpChannel(props, clientProvider, serverProvider);
            ChannelServices.RegisterChannel(Chan);

            String url = "tcp://" + ip + ":" + portaServidor + "/" + projeto;

            Type typeofRI = typeof(InterfaceRemota.IServidor);
            InterfaceRemota.IServidor objRemoto =
                (InterfaceRemota.IServidor)Activator.GetObject(typeofRI, url);

            return objRemoto;
        }
    }
}
